/**
 * 本地存储工具类
 */
export class StroageUtil {
    /**
     * 获取number类型的本地存储值
     */
    public static getNumber(key: number | string, defaultValue: number = 0): number {
        let value = parseFloat(cc.sys.localStorage.getItem(key));
        return isNaN(value) ? defaultValue : value;
    }

    /**
     * 获取string类型的本地存储值
     */
    public static getString(key: number | string, defaultValue: string = ""): string {
        let value = cc.sys.localStorage.getItem(key) + "";
        if (value) {
            return value;
        }
        return defaultValue;
    }

    /**
     * 获取boolean类型的本地存储值
     */
    public static getBoolean(key: number | string, defaultValue: boolean = false): boolean {
        let value = cc.sys.localStorage.getItem(key) + "";
        if (value != "true" && value != "false") {
            return defaultValue;
        } else {
            return value != "false";
        }
    }

    /**
     * 获取object类型的本地存储值
     */
    public static getObject(key: number | string, defaultValue: object = null): any {
        let value = cc.sys.localStorage.getItem(key);
        try {
            value = JSON.parse(value);
        } catch (err) {
            console.error(key, ": JSON.parse转化对象错误 ", value);
            value = defaultValue;
        }
        return value;
    }

    /**
     * 设置本地存储值
     */
    public static setValue(key: number | string, value: number | string | boolean | object) {
        if (typeof value == "object") {
            value = JSON.stringify(value);
        }
        cc.sys.localStorage.setItem(key, value);
    }

    //清除缓存
    public static removeItem(key: number | string): void {
        cc.sys.localStorage.removeItem(key);
    }
}
